package com.ebo.agora.openvcall;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;

import com.ebo.agora.openvcall.model.CurrentUserSettings;
import com.ebo.agora.openvcall.model.WorkerThread;
import com.ebo.download.download2.DownloadReceiver;
import com.iflytek.cloud.Setting;
import com.iflytek.cloud.SpeechUtility;
import com.uzmap.pkg.openapi.APICloud;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import utils.DensityUtil;

public class AGApplication extends Application implements DownloadReceiver.MyContext {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private static Context instance;
    public static String InstallApkName;

    public static Context getInstance() {
        return instance;
    }

    private static List<Activity> oList;//用于存放所有启动的Activity的集合
    //虚拟按键宽度
    public static int getBottomStatusHeight;
    public static SpeechUtility tt;
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        registerDownload();


//         SpeechEvaluator mIse = SpeechEvaluator.createEvaluator(AGApplication.this, null);
//        if(tt==null){
//            Lg.d("NNNNNNNNNNNNNN");
//        }
//        init();
//        System.out.println("LGY hasBar =" + Pub.hasNavBar(instance)+",getDpi="+Pub.getDpi(instance)+",getBottomStatusHeight="+Pub.getBottomStatusHeight(instance)+",getTitleHeight="
//                +Pub.getStatusHeight(instance)+",getScreenHeight="+Pub.getScreenHeight(instance)+",");
    }

    public static void init() {

        oList = new ArrayList<Activity>();
        RongIM.init(instance);
        APICloud.initialize(instance);//初始化APICloud，SDK中所有的API均需要初始化后方可调用执行

        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(instance);            // 初始化 JPush
        getBottomStatusHeight = DensityUtil.getBottomStatusHeight(instance);
        //讯飞
        SpeechUtility.createUtility(instance, "appid=5931266a" );
        Setting.setShowLog(false);

    }

    //下载完成后的广播
    DownloadReceiver myReceiver;

    private void registerDownload() {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.ebo.action.Finish_Download");
        myReceiver = new DownloadReceiver();
        registerReceiver(myReceiver, intentFilter);
        myReceiver.setMyActivityListener(this);
    }

    @Override
    public void onTerminate() {
        unregisterReceiver(myReceiver);
        super.onTerminate();
    }

    private static WorkerThread mWorkerThread;

    public synchronized void initWorkerThread() {
        if (mWorkerThread == null) {
            mWorkerThread = new WorkerThread(getApplicationContext());
            mWorkerThread.start();

            mWorkerThread.waitForReady();
        }
    }

    public synchronized WorkerThread getWorkerThread() {
        return mWorkerThread;
    }

    public synchronized void deInitWorkerThread() {
        mWorkerThread.exit();
        try {
            mWorkerThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mWorkerThread = null;
    }

    public static final CurrentUserSettings mVideoSettings = new CurrentUserSettings();


    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {

                return appProcess.processName;
            }
        }
        return null;
    }


    /**
     * 添加Activity
     */
    public void addActivity_(Activity activity) {
// 判断当前集合中不存在该Activity
        if (!oList.contains(activity)) {
            oList.add(activity);//把当前Activity添加到集合中
        }
    }

    /**
     * 销毁单个Activity
     */
    public void removeActivity_(Activity activity) {
//判断当前集合中存在该Activity
        if (oList.contains(activity)) {
            oList.remove(activity);//从集合中移除
            activity.finish();//销毁当前Activity
        }
    }

    /**
     * 销毁所有的Activity
     */
    public void removeALLActivity_() {
        //通过循环，把集合中的所有Activity销毁
        for (Activity activity : oList) {
            activity.finish();
        }
    }

    @Override
    public void onDownloadResult(int result, final String filepath) {
        switch (result) {
            case 1:
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Message message = new Message();
                        message.what = 1;
                        message.getData().putString("fliepath", filepath);
                        mHandler.sendMessage(message);
                    }
                });
                thread.start();
                break;
        }
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    final String _fliepath = msg.getData().getString("fliepath");
//                    Lg.d("fliepath = "+_fliepath);
                    InstallApkName = _fliepath.substring(_fliepath.lastIndexOf("/") + 1);
//                    Lg.d("InstallApkName="+InstallApkName);

                    Intent intent = new Intent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    Uri uri = Uri.fromFile(new File(_fliepath));
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    startActivity(intent);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

}
